package com.hd.trans.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * create by:朱玉才
 * on:2020/12/13
 * Description:防止重复性点击按钮
 */
public class CheckDoubleClick {
    private static Map<String, Long> records = new HashMap<>();
    private static long lastTime;

    public static boolean isFastDoubleClick() {
        //本方法被调用的文件名和行号作为标记
        StackTraceElement ste = new Throwable().getStackTrace()[1];
        long timeDuration = doSomething(ste);
        return 0 < timeDuration && timeDuration < 500;
    }

    public static boolean isIntervalClick(int interval) {
        //本方法被调用的文件名和行号作为标记
        StackTraceElement ste = new Throwable().getStackTrace()[1];
        String key = ste.getFileName() + ste.getLineNumber();
        Long lastClickTime = records.get(key);
        if (lastClickTime == null) {
            lastClickTime = 0L;
        }
        long thisClickTime = System.currentTimeMillis();
        long timeDuration = thisClickTime - lastClickTime;
        if(0 < timeDuration && timeDuration < interval){
            return false;
        }
        records.put(key, thisClickTime);
        return true;
    }

    public static boolean isDoubleRunning(){
        long thisTime = System.currentTimeMillis();
        if((thisTime - lastTime)<1000){
            lastTime = thisTime;
            return true;
        }
        lastTime = thisTime;
        return false;
    }

    private static long doSomething(StackTraceElement ste){
        if (records.size() > 1000) {
            records.clear();
        }

        String key = ste.getFileName() + ste.getLineNumber();

        Long lastClickTime = records.get(key);
        long thisClickTime = System.currentTimeMillis();
        records.put(key, thisClickTime);
        if (lastClickTime == null) {
            lastClickTime = 0L;
        }
        return thisClickTime - lastClickTime;
    }
}
